#include "PlacePanel.h"
#include "ResourcesManager.h"
#include "TowerManager.h"
#include "CoinManager.h"
#include "Tile.h"
#include "SDL2_gfxPrimitives.h"

PlacePanel::PlacePanel()
{
    const ResourcesManager::TexturePool &texturePool = ResourcesManager::Instance().texturePool;

    texIdle = texturePool.find(ResID::Tex_UIPlaceIdle)->second;
    texHoveredTop = texturePool.find(ResID::Tex_UIPlaceHoveredTop)->second;
    texHoveredLeft = texturePool.find(ResID::Tex_UIPlaceHoveredLeft)->second;
    texHoveredRight = texturePool.find(ResID::Tex_UIPlaceHoveredRight)->second;
}

void PlacePanel::OnUpdate(SDL_Renderer *renderer)
{
    static TowerManager &instance = TowerManager::Instance();

    valTop = (int) instance.GetPlaceCost(TowerType::Axeman);
    valLeft = (int) instance.GetPlaceCost(TowerType::Archer);
    valRight = (int) instance.GetPlaceCost(TowerType::Gunner);

    regTop = (int) instance.GetDamageRange(TowerType::Axeman) * SIZE_TILE;
    regLeft = (int) instance.GetDamageRange(TowerType::Archer) * SIZE_TILE;
    regRight = (int) instance.GetDamageRange(TowerType::Gunner) * SIZE_TILE;

    Panel::OnUpdate(renderer);
}

void PlacePanel::OnRender(SDL_Renderer *renderer)
{
    if (!visible) return;

    int reg = 0;
    switch (hoveredTarget) {
        case Panel::HoveredTarget::Top:
            reg = regTop;
            break;
        case Panel::HoveredTarget::Left:
            reg = regLeft;
            break;
        case Panel::HoveredTarget::Right:
            reg = regRight;
            break;
    }

    if (reg > 0) {
        filledCircleRGBA(renderer, centerPos.x, centerPos.y, reg,
                         colorRegionContent.r, colorRegionContent.g, colorRegionContent.b, colorRegionContent.a);
        aacircleRGBA(renderer, centerPos.x, centerPos.y, reg,
                     colorRegionFrame.r, colorRegionFrame.g, colorRegionFrame.b, colorRegionFrame.a);
    }

    Panel::OnRender(renderer);
}

void PlacePanel::OnClickTopArea()
{
    CoinManager &instance = CoinManager::Instance();

    if (valTop <= instance.GetCurrentCoinNum()) {
        TowerManager::Instance().PlaceTower(TowerType::Axeman, idxTileSelected);
        instance.DecreaseCoin(valTop);
    }
}

void PlacePanel::OnClickLeftArea()
{
    CoinManager &instance = CoinManager::Instance();

    if (valLeft <= instance.GetCurrentCoinNum()) {
        TowerManager::Instance().PlaceTower(TowerType::Archer, idxTileSelected);
        instance.DecreaseCoin(valLeft);
    }
}

void PlacePanel::OnClickRightArea()
{
    CoinManager &instance = CoinManager::Instance();

    if (valRight <= instance.GetCurrentCoinNum()) {
        TowerManager::Instance().PlaceTower(TowerType::Gunner, idxTileSelected);
        instance.DecreaseCoin(valRight);
    }
}